<template>
  <div class="app-container app-container-next">
    <div class="el-card box-card is-false-shadow">
      <sticky-header :style="{height: '40px'}" :top="230">
        <div class="el-card__header sticky-header"
             style="display: flex;justify-content: space-between;align-items: center;background: #fff">
          <router-link :to="{name: 'top-good-list'}">
            <el-button :round="true" icon="el-icon-back" plain size="small">
              返回
            </el-button>
          </router-link>
          <el-button type="primary" @click="saveData('submitForm')">保存数据</el-button>
        </div>
      </sticky-header>
      <el-row>
        <el-col :span="18">
          <el-form ref="submitForm" :model="topGood" :rules="rules" label-width="120px">
            <h4>基本信息</h4>
            <el-form-item label="链接名称" prop="name">
              <el-input v-model="topGood.name" placeholder="请输入链接名称" style="width: 400px" maxlength="25"/>
            </el-form-item>
            <el-form-item label="fbclid" prop="keyWords">
              <el-input v-model="topGood.keyWords" placeholder="请输入店匠fb推广链接的fbclid参数" style="width: 400px"
                        maxlength="100"/>
            </el-form-item>
            <el-form-item label="系列名称">
              <el-select v-model="topGood.seriesId" placeholder="请选择">
                <el-option
                    v-for="item in oneSeriesOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <h4>置顶商品  <el-button size="mini"  type="primary" @click="openDrawer1">选择商品</el-button></h4>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <el-table :data="defaultProductList" style="width: 100%" class="drag-table" row-key="id"
              ref="multipleTable">
      <el-table-column label="商品图片"  width="180px">
        <template slot-scope="{row}">
          <div style="display: flex;align-items: center">
            <svg-icon icon-class="grid" class="icon"></svg-icon>
            <el-image
                style="width: 80px; height: 60px;"
                :src="row.mainImage"
                :preview-src-list="[row.mainImage]"
                fit="contain"></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="spuName" label="商品名称" width="500"></el-table-column>
      <el-table-column prop="sellPrice" label="售价">
        <template slot-scope="{row}">
          <p>{{ row.sellPrice|currency(currencySymbol) }}</p>
        </template>
      </el-table-column>
      <el-table-column prop="publishText" label="上架状态"></el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" plain type="danger" @click="handleRemove(scope.row.id)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-drawer
        size="1000px"
        :title="drawer1Title"
        :wrapperClosable="false"
        :visible.sync="drawer1Visible"
        @close="handleClose"
        class="region-setting-panel">
      <div style="padding-bottom: 80px">
        <el-form ref="freightDetailForm" label-width="100px" class="demo-ruleForm" label-position="top">
          <el-form ref="form" label-width="80px">
            <el-form-item class="el-form--inline" style="margin-left: -70px">
              <el-select v-model="pageSearch.spuSeries" placeholder="请选择" @change="searchSpuInfo(true)" style="width: 160px">
                <el-option
                    v-for="item in seriesOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                </el-option>
              </el-select>
              <el-select v-model="pageSearch.spuType" placeholder="请选择"  @change="searchSpuInfo(true)" style="width: 160px">
                <el-option value="" label="全部商品"></el-option>
                <el-option value="0" label="普通商品"></el-option>
                <el-option value="1" label="定制商品"></el-option>
              </el-select>
              <el-input v-model="pageSearch.spuName" placeholder="商品名称" style="width: 220px" @keyup.enter.native="searchSpuInfo(true)"></el-input>
              <!--              <el-select v-model="pageSearch.published" placeholder="请选择" @change="searchSpuInfo(true)" style="width: 120px">
                              <el-option
                                  v-for="item in publishStatus"
                                  :key="item.key"
                                  :label="item.name"
                                  :value="item.key">
                              </el-option>
                            </el-select>-->
              <el-input v-model="pageSearch.spuCode" placeholder="SPU编码,多个值以','分割"  @keyup.enter.native="searchSpuInfo(true)" style="width: 220px"></el-input>
              <el-button type="primary" @click="searchSpuInfo">搜索</el-button>
              <el-button @click="resetSearchInfo">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="productList" style="width: 100%" @select="handleSelectionChange" @select-all="handleSelectionChangeAll" height="height: 500px"
                    v-el-height-adaptive-table="fixOption"
                    v-loading="tableLoading"
                    v-loadmore="loadMore"
                    ref="multipleTable">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="商品图片" width="100px">
              <template slot-scope="{row}">
                <el-image
                    style="width: 80px; height: 60px;"
                    :src="row.mainImage"
                    :preview-src-list="[row.mainImage]"
                    fit="contain"></el-image>
              </template>
            </el-table-column>
            <el-table-column prop="spuName" label="商品名称" width="380"></el-table-column>
            <el-table-column prop="sellPrice" label="售价">
              <template slot-scope="{row}">
                <p>{{ row.sellPrice|currency(currencySymbol) }}</p>
              </template>
            </el-table-column>
            <el-table-column prop="publishText" label="上架状态"></el-table-column>
          </el-table>
          <div class="footer">
            <div>最多选20件商品已选择了{{ defaultProductList.length + chooseProductList.length }}件&nbsp;</div>
            <el-button type="primary" @click="closeDrawerAndSaveData">添加</el-button>
          </div>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import Sortable from 'sortablejs';
import stickyHeader from '_c/StickyHeader';
import {editTopGood, getDataById} from '@/api/top-good';
import {getSeriesPage} from '@/api/series';
import {getSpuPage} from '@/api/goods';
import {mapGetters} from 'vuex';
import elHeightAdaptiveTable from '@/directives/el-table';
import {currency} from '@/utils/filters';

export default {
    name: 'top-good-edit',
    directives: {
        elHeightAdaptiveTable
    },
    // eslint-disable-next-line vue/no-unused-components
    components: {stickyHeader},
    data: function () {
        return {
            fixOption: {fixedHeader: true, bottomOffset: 80},
            tableLoading: false,
            topGoodId: this.$route.params.id,
            topGood: {
                siteId: '',
                name: '',
                seriesId: '',
                spuIds: [],
                keyWords: ''
            },
            oneSeriesOptions: [],
            seriesOptions: [{id: '', name: '全部系列'}],
            publishStatus: [
                {key: '', name: '全部状态'},
                {key: 1, name: '上架'},
                {key: 0, name: '下架'},
                {key: -1, name: '未上架'}
            ],
            drawer1Title: '选择商品',
            drawer1Visible: false,
            rules: {
                name: [
                    {required: true, message: '请填写链接名称', trigger: 'blur'}
                ],
                seriesId: [
                    {required: true, message: '请选择系列', trigger: 'blur'}
                ]
            },
            submitLoading: false,
            defaultProductList: [],
            chooseProductList: [],
            pageSearch: {
                page: 1,
                pageSize: 20,
                spuType: '',
                spuSeries: '',
                published: '',
                spuCode: '',
                spuName: ''
            },
            totalElements: 0,
            totalPage: 0,
            productList: [],
            tips: '0',
            tempList: [],
            removeList: []
        };
    },
    methods: {
        handleReset (name) {
            this.$router.push({name: name});
        },
        handleRemove (id) {
            const index = this.defaultProductList.findIndex(res => res.id === id);
            this.defaultProductList.splice(index, 1);
        },
        openDrawer1 () {
            this.drawer1Visible = true;
            this.searchSpuInfo(true);
        },
        closeDrawerAndSaveData () {
            if ((this.chooseProductList.length + this.defaultProductList.length) > 20) {
                this.$message.error('已超过商品选择最大值，请修改后重新确认');
                return;
            }
            this.drawer1Visible = false;
            this.defaultProductList = this.defaultProductList.concat(this.chooseProductList);
            this.chooseProductList = [];
        },
        handleClose () {
            this.chooseProductList = [];
        },
        loadMore () {
            console.log('el-table 已经滚到底部');
            this.pageSearch.page++;
            if (this.pageSearch.page > this.totalPage) {
                return;
            }
            this.searchSpuInfo();
        },
        saveData (formName) {
            this.topGood.siteId = this.siteId;
            this.topGood.spuIds = this.defaultProductList.map(s => s.id);
            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.submitLoading = true;
                    if (this.topGood.seriesId === undefined || this.topGood.seriesId === '') {
                        this.$message.error('请选择主系列');
                        return;
                    }
                    if (this.topGood.spuIds.length === 0) {
                        this.$message.error('选择商品不能为空');
                        return;
                    }
                    editTopGood(this.topGood).then(res => {
                        if (res.code === '200') {
                            this.submitLoading = false;
                            this.$message.success('修改成功');
                            this.handleReset('top-good-list');
                        }
                    }).catch(() => {
                        this.submitLoading = false;
                    });
                }
            });
        },
        selectDefaultProduct () {
            this.tableLoading = true;
            let defaultSpuIds = this.defaultProductList.map(s => s.id);
            let check = this.productList.filter(s => defaultSpuIds.includes(s.id));
            this.$nextTick(() => {
                if (check) {
                    check.forEach(index => {
                        this.$refs.multipleTable.toggleRowSelection(index);
                    });
                }
            });
            this.tableLoading = false;
        },
        getAllSeries () {
            let json = {
                page: 1,
                pageSize: 1000,
                siteId: this.siteId
            };
            getSeriesPage(json).then(res => {
                this.oneSeriesOptions = res.records;
                res.records.forEach(s => {
                    this.seriesOptions.push(s);
                });
            });
        },
        handleSelectionChange (rows, row) {
            let selected = rows.length && rows.indexOf(row) !== -1;
            let obj = {};
            let data = [...this.chooseProductList, ...rows].reduce((cur, next) => {
                // eslint-disable-next-line no-unused-expressions
                obj[next.id] ? '' : obj[next.id] = true && cur.push(next);
                return cur;
            }, []);
            const index = data.findIndex(s => s.id === row.id);
            if (!selected) {
                data.splice(index, 1);
            }
            this.chooseProductList = data;
        },
        handleSelectionChangeAll (rows) {
            this.chooseProductList = rows;
        },
        handleSizeChange (val) {
            console.log(`每页 ${val} 条`);
            this.searchSpuInfo();
        },
        handleCurrentChange (val) {
            console.log(`当前页: ${val}`);
            this.pageSearch.page = val;
            this.searchSpuInfo();
        },
        searchSpuInfo (flag = false) {
            if (flag) {
                this.pageSearch.page = 1;
            }

            this.tableLoading = true;
            this.pageSearch.siteId = this.siteId;
            console.log(this.defaultProductList);
            this.pageSearch.notSpuIdList = this.defaultProductList.length ? this.defaultProductList.map(res => res.id).join(',') : '';
            getSpuPage(this.pageSearch).then(res => {
                this.productList = flag ? res.records : this.productList.concat(res.records);
                this.totalPage = res.totalpage;
                this.tableLoading = false;
                this.$nextTick(() => {
                    console.log(this.chooseProductList);
                    const list = this.productList.filter(s => this.chooseProductList.some(n => n.id === s.id));
                    list.forEach(index => {
                        this.$refs.multipleTable.toggleRowSelection(index, true);
                    });
                });
            });
        },
        resetSearchInfo () {
            this.pageSearch = {
                page: 1,
                pageSize: 20,
                seriesId: '',
                spuType: '',
                published: '',
                spuCode: '',
                spuName: ''
            };
            this.searchSpuInfo();
        },
        getDataById () {
            getDataById(this.topGoodId).then(res => {
                this.topGood = res.data;
                this.defaultProductList = res.data.topGoodSpuVOS;
                // this.$nextTick(() => {
                //     this.drag();
                // });
            });
        },
        drag () {
        // 首先获取需要拖拽的dom节点
            const el1 = document.querySelectorAll('.drag-table .el-table__body-wrapper')[0].querySelectorAll('table > tbody')[0];
            Sortable.create(el1, {
                disabled: false, // 是否开启拖拽
                forceFallback: true,
                scroll: true,
                ghostClass: 'sortable-ghost', // 拖拽样式
                animation: 150, // 拖拽延时，效果更好看
                group: { // 是否开启跨表拖拽
                    pull: false,
                    put: false
                },
                onEnd: (e) => { // 这里主要进行数据的处理，拖拽实际并不会改变绑定数据的顺序，这里需要自己做数据的顺序更改
                    let arr = this.defaultProductList; // 获取表数据
                    arr.splice(e.newIndex, 0, arr.splice(e.oldIndex, 1)[0]); // 数据处理
                    this.$nextTick(function () {
                        this.defaultProductList = arr;
                    });
                }
            });
        }
    },
    created () {
        this.$nextTick(() => {
            this.getAllSeries();
            this.getDataById();
        });
    },
    mounted () {
        this.drag();
    },
    computed: {
        ...mapGetters(['siteList', 'timeZone']),
        siteId () {
            return this.$store.state.user.siteId;
        },
        siteInfo () {
            let info = this.siteList.find(res => res.id === Number(this.siteId));
            return info;
        },
        currencySymbol () {
            return this.siteInfo.currencySymbol;
        }
    }
};

</script>

<style lang="scss" scoped>
.region-setting-panel{
  .block{
    text-align: right;
    padding-top: 12px;
    padding-bottom: 6px;
  }
  .footer {
    z-index: 222;
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 70px;
    background: #eef0f5;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 20px;
    padding-left: 20px;
  }
}

</style>
